<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal } from '@/static/js/common.js';
import {buildFormData,getEditorTitle, hasEditor,formValidation, tranferToEditors, changeEditor,setSubmitSubValue, configSelectData, hasValue,formShowLoading ,getFormFields,formModelLoad,getWorkCacheKey} from '@/static/js/formUtil.js';
import urlUtil from '@/static/js/urlUtil.js';
import { mapState, mapActions } from 'pinia';
import {useLoginUserStore} from '@/stores/login-user.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			INST_ID:"",
			initItemName:"",
			fileId:""
		})
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId']),
	},
	watch:{
	
	},
	methods: {
		...mapActions(useLoginUserStore, [
			'setRecentWork'
		]),
		formSubmit() {
			let workList = this.subEditorObj["itemInfo"].workList
			let msTitle = this.$refs.autoform.getEditorTitle("itemInfo")
			if (!workList.length) {
				this.om.toast('请配置' + msTitle);
				return;
			}
			var nopoint = []
			workList.filter((e,i)=>{
				if(!hasValue(e.score) || !e.score){
					nopoint.push(i+1)
				}
			})
			workList.forEach(e=>{
				if(!e.files){
					e.files = []
				}
				if(!e.fileList){
					e.fileList = []
				}
			})
			
			if(nopoint.length){
				let _that = this;
				var title = nopoint.length > 10?
				"第"+nopoint.slice(0,3).join("、")+"等"+nopoint.length+"条数据没有评分，默认将赋0，确认保存吗？":
				"第"+nopoint.join("、")+"共计"+nopoint.length+"条数据没有评分，默认将赋0，确认保存吗？"
				
				confirmModal(_that, "保存前提示", title, function() {
					_that.$set(_that.formdata,"objStr",JSON.stringify(workList))
					_that.om.formSave('tkeyWorkEvaluate/addTkeyWorkEvaluate', _that.formdata, _that);
				})
			}else{
				let _that = this
				_that.$set(_that.formdata,"objStr",JSON.stringify(workList))
				this.om.formSave('tkeyWorkEvaluate/addTkeyWorkEvaluate', this.formdata, this, function(id){
					if(_that.initItemName && workList.filter(e => _that.initItemName === e.itemName).length){
						_that.setRecentWork(true)
					}
					_that.om.getFormInfo(id, _that.busCode, true);
				});
			}
		},
		getWorkParam() {
			return  {
				editId:this.fileId,
				instId: this.formdata.instId,
				userId: this.formdata.instUserId
			}
		},
		//被评价机构选择之后
		onSelectInst(item) {
			let _that = this
			_that.$refs.autoform.clear('instInfo', 'instUserId');
			_that.subEditorObj['itemInfo'].workList = []
			_that.getInfoUsers(item.id)
			_that.loadSubData();
		},
		
		getInfoUsers(id){
			let _that = this;
			this.om
				.request('tkeyWorkEvaluate/getUserList', {
					instId:id
				})
				.then(res => {
					_that.$refs.autoform.changeEditor('instInfo', 'instUserId', 'data', configSelectData(res, 'id', 'username'));
					_that.$refs.autoform.initSelectIndex("instInfo","instUserId")
				});
		},
		onSelectUser(){
			let _that = this;
			if(!_that.$refs.autoform.formdata.instId){
				var instIdTitle = _that.$refs.autoform.getEditorTitle("instInfo", "instId")
				_that.om.toast("请选择" + instIdTitle)
				_that.subEditorObj['itemInfo'].workList = []
				return
			}
			this.loadSubData();
		},
		clearInst(){
			this.$refs.autoform.clear('instInfo', 'instId');
			this.$refs.autoform.clear('instInfo', 'instUserId');
			this.$refs.autoform.changeEditor('instInfo', 'instUserId', 'data',[])
			this.subEditorObj['itemInfo'].workList = []
		},
		clearInstUser(){
			this.$refs.autoform.clear('instInfo', 'instUserId');
			this.subEditorObj['itemInfo'].workList = [];
			this.loadSubData();
		},
		loadSubData(){
			let _that = this;
			this.om
				.request('tkeyWorkEvaluate/getDataList', {
					zposId: _that.$refs.autoform.formdata.zposId,
					instId: _that.$refs.autoform.formdata.instId,
					userId: _that.$refs.autoform.formdata.instUserId,
				},'get',true)
				.then(data => {
					if (data.succeed && data.value.length > 0) {
						this.subEditorObj['itemInfo'].workList = data.value
					} else {
						this.subEditorObj['itemInfo'].workList = []
						_that.om.toast("待评价数据为空");
					}
				});
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				{url:'tkeyWorkEvaluate/instList'}
			];
			var itemid = options.itemid
			let fileId= options.fileId
			_that.fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:"tkeyWorkEvaluate/getInfo",
					param:{
						id:fileId
					},
					method:"post"
				})
			}
			if(itemid){
				ajaxArr.push({
					url:"tkeyWorkEvaluate/getUnfinishWork",
					param:{
						listId: itemid
					}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('instInfo', 'instId', 'data', configSelectData(res[0], 'id', 'instName'),mainData);
				if(_that.subEditorObj["itemInfo"]){
					let attr = {
						getWorkParam: 'getWorkParam',
						titleTemplate:" <%= '工作项名称:' +  itemName%> " + "<%= score? ('得分：' + score):'未评分' %>",
						subtitle1Template:"<%= workStandard %>",
						subtitle2Template:"<%= planEndDate?'计划'+planEndDate+'完成，':'' %> <%= actualEndDate?'实际'+actualEndDate+'完成':'实际完成时间未填写' %>"
					}
					let configData = _that.subConfigData["itemInfo"]
					let title = getEditorTitle("itemInfo",'evaluateResultId',configData)
					if(hasEditor("itemInfo",'evaluateResultId',configData)){
						attr.subtitle3Template=title + ":<%= evaluateResultName ?  evaluateResultName : '无'%>"
					}
					changeEditor("itemInfo", "objStr",attr, mainData)
				}
				if(fileId){
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id","userName","userId")
					for(var item in res[1].value.tkeyWorkEvaluate){
						if(fieldArr.includes(item)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,item,res[1].value.tkeyWorkEvaluate[item])
						}
					}
					for(var index in res[1].value.tkeyWorkEvaluate_data){
						for(var item in  res[1].value.tkeyWorkEvaluate_data[index]){
							if(fieldArr.includes(item)){
								if(item === "id"){
									continue
								}else{
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,item,res[1].value.tkeyWorkEvaluate_data[index][item])
								}
							}
						}
					}
					var dataList = _that._.cloneDeep(res[1].value.tkeyWorkEvaluate_data)
					_that.subEditorObj["itemInfo"].workList = dataList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr", JSON.stringify(dataList))
					_that.$set(_that.formdata, "objStr", JSON.stringify(dataList))
					delete res[1].value.dataList
					_that.$nextTick(function(){
						_that.$refs.autoform.initSelectIndex("instInfo","instId")
						_that.getInfoUsers(res[1].value.tkeyWorkEvaluate.instId)
					})
				}
				if(itemid){
					var it = null
					if(fileId){
						it = res[2].value
					}else{
						it = res[1]
					}
					if(it && it.length>0){
						var obj = {
							tkeyWorkListId:it[0].tkeyWorkListId,
							orderNum:it[0].orderNum,
							itemName:it[0].itemName,
							workStandard:it[0].workStandard,
							deliveryName:it[0].deliveryName,
							keyItem:it[0].keyItem?'√':'',
							deliveryName:it[0].deliveryName,
							planEndDate:it[0].planEndDate,
							actualEndDate:it[0].actualEndDate,
							evaluateResultId:it[0].evaluateResultId,
							evaluateResultName:it[0].evaluateResultName,
							userId:it[0].userId,
							userName:it[0].userName,
							posId:it[0].posId,
							posName:it[0].posName,
							evaluateUserId:it[0].evaluateUserId,
							evaluateUserName:it[0].evaluateUserName,
							remark:it[0].remark,
							files:it[0].files,
							maxScore:it[0].maxScore,
							score:it[0].score
						}
						_that.initItemName = it.workName
						_that.subEditorObj["itemInfo"].workList = [obj]
						_that.om
							.request('tkeyWorkEvaluate/getUserList', {
								instId:it[0].dataInstId?it[0].dataInstId:''
							})
							.then(res => {
								_that.$refs.autoform.changeEditor('instInfo', 'instUserId', 'data', configSelectData(res, 'id', 'username'));
								_that.$refs.autoform.formdata.instId = it[0].dataInstId
								_that.$refs.autoform.formdata.instName = it[0].instName
								_that.$refs.autoform.formdata.instUserId = it[0].userId
								_that.$refs.autoform.formdata.instUserName = it[0].userName
								_that.$refs.autoform.initSelectIndex('instInfo', 'instId')
								_that.$refs.autoform.initSelectIndex('instInfo', 'instUserId')
							});
					}
				}
				_that.$nextTick(function(){
					if(!itemid){
						if(!_that.$refs.autoform.formdata.instId){
							_that.$refs.autoform.initSelectVal("instInfo","instId")
						}else{
							_that.$refs.autoform.initSelectIndex("instInfo","instId")
						}
					}
				})
			},options)
			
		}
	},
	onLoad(options) {
		let _that = this;
		_that.initValue.zuserId = this.userId;
		_that.initValue.zuserName = this.userName;
		_that.initLoad(options);
	},
	onUnload(){
		//#ifdef APP-PLUS
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				uni.removeStorage({
					key: getWorkCacheKey(fieldId)
				});
			}
		}
		//#endif
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				let editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
		}
	}
};
</script>
<style></style>
